package com.example.huichaoliu;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.huichaoliu.app.R;
import com.huichaoliu.data.Config;
import com.huichaoliu.data.UserInfo;
import com.rederxu.AsyncTask.ImageTask;
import com.rederxu.farmer.BaseActivity;
import com.rederxu.request.HTTPRequest;
import com.rederxu.request.onRequestOverListener;
import com.source.utils.Utils;

public class EnsureOrderActivity extends BaseActivity implements OnClickListener {
	
	private JSONArray ja = new JSONArray();
	private ListView listView = null;
	private JSONObject joAddress = null;
	private TextView tv_address_name = null;
	private TextView tv_address_mobile = null;
	private TextView tv_address = null;
	private final int CODE_BACK_FROM_SELECT_ADDRESS = 100;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_order_ensure);
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.left_button:
			finish();
			break;
		case R.id.btn_go:
			try{
				if(joAddress == null){
					showToast("请正确添加并选择收货地址后下单");
					return;
				}
				JSONObject jo = new JSONObject();
				jo.put("userId", Config.getUserId(mContext));
				jo.put("addressId", joAddress.getString("addressId"));
				JSONArray jaCommoditys = new JSONArray();
				for(int i = 0; i < ja.length();i++){
					JSONObject joCommoditys = ja.getJSONObject(i).getJSONObject("commodity");
					JSONObject joNumber = ja.getJSONObject(i).getJSONObject("number");
					JSONObject joCommoditysNew = new JSONObject();
					joCommoditysNew.put("commodityId", joCommoditys.getString("commodityId"));
					joCommoditysNew.put("numberId", joNumber.getInt("id"));
					try{
						int number = joNumber.getInt("num_buy");
						joCommoditysNew.put("number", number);
					}catch(Exception e){
						joCommoditysNew.put("number", 1);
					}
					jaCommoditys.put(joCommoditysNew);
				}
				jo.put("commoditys", jaCommoditys);
				Bundle bundle = new Bundle();
				bundle.putString("request", Utils.requestParamsEncode(jo));
				HTTPRequest.POST(this, Config.REQUEST_URLS.URL_ORDER_ADD, bundle, new onRequestOverListener() {
					@Override
					public void onRequestOver(String result) {
						try{
							Log.e("result", result);
							JSONObject jo = new JSONObject(result);
							showToast(jo.getString("message"));
							if(jo.getInt("code") != 0){
								return;
							}
							startActivity(PayActivity.class);
						}catch(JSONException e){
							e.printStackTrace();
						}
					}
				});
			}catch(Exception e){
				e.printStackTrace();
			}
			break;
		case R.id.layout_address_1:
		case R.id.layout_address_2:
			Intent i = new Intent(mContext,ReceiptAddressActivity.class);
			i.putExtra("isSelect", true);
			startActivityForResult(i, CODE_BACK_FROM_SELECT_ADDRESS);
			break;
		}
	}

	@Override
	public void init() {
		((TextView) findViewById(R.id.title_text)).setText("确认订单");
		findViewById(R.id.left_button).setOnClickListener(this);
		findViewById(R.id.btn_go).setOnClickListener(this);
		listView = (ListView) findViewById(R.id.listView);
		tv_address = (TextView) findViewById(R.id.tv_address);
		tv_address_name = (TextView) findViewById(R.id.tv_address_name);
		tv_address_mobile = (TextView) findViewById(R.id.tv_address_mobile);
	}

	@Override
	public void initData() {
		try {
			ja = new JSONArray(getIntent().getStringExtra("data"));
			listView.setAdapter(new Adapter());
		} catch (JSONException e) {
			showToast("商品信息获取失败");
			e.printStackTrace();
			ja = new JSONArray();
			finish();
		}

		try{
			UserInfo info = new UserInfo(this);
			JSONObject jo = new JSONObject();
			jo.put("userId", info.getUid());
			Bundle bundle = new Bundle();
			bundle.putString("request", Utils.requestParamsEncode(jo));
			HTTPRequest.POST(this, Config.REQUEST_URLS.URL_USER_ADDRESS_LIST, bundle, new onRequestOverListener() {
				@Override
				public void onRequestOver(String result) {
					try{
						JSONObject jo = new JSONObject(result);
						if(jo.getInt("code") != 0){
							showToast(jo.getString("message"));
							return;
						}
						JSONArray ja = jo.getJSONArray("response");
						for(int i = 0; i < ja.length();i++){
							jo = ja.getJSONObject(i);
							if(jo.getBoolean("iscommon")){
								joAddress = jo;
							}
						}
						if(joAddress != null){
							tv_address.setText(joAddress.getString("address"));
							tv_address_name.setText(joAddress.getString("name"));
							tv_address_mobile.setText(joAddress.getString("phone"));
						}
					}catch(JSONException e){
						e.printStackTrace();
					}
				}
			});
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void onNetworkChanged(boolean isMobNetConnected,
			boolean isWifiConnected) {
		// TODO Auto-generated method stub

	}

	private class Adapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return ja.length();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.item_ensure_order, null);
			}
			TextView tv_order_num = (TextView) convertView.findViewById(R.id.tv_order_num);
			TextView tv_info = (TextView) convertView.findViewById(R.id.tv_info);
			TextView tv_price = (TextView) convertView.findViewById(R.id.tv_price);
			final TextView tv_money_total = (TextView) convertView.findViewById(R.id.tv_money_total);
			TextView tv_count = (TextView) convertView.findViewById(R.id.tv_count);
			TextView tv_add = (TextView) convertView.findViewById(R.id.tv_add);
			TextView tv_divide = (TextView) convertView.findViewById(R.id.tv_divide);
			ImageView ic_cover = (ImageView) convertView.findViewById(R.id.ic_cover);
			View layout_insurance = convertView.findViewById(R.id.layout_insurance);
			View layout_preferential = convertView.findViewById(R.id.layout_preferential);
			final EditText et_num = (EditText) convertView.findViewById(R.id.et_num);
			try{
				final JSONObject joCommodity = ja.getJSONObject(position).getJSONObject("commodity");
				final JSONObject joNumber = ja.getJSONObject(position).getJSONObject("number");
				tv_order_num.setText("{  订  单  " + (position + 1) + "  }");
				tv_info.setText(joCommodity.getString("name") + "-" + joNumber.getString("color") + "  " + joNumber.getString("size"));
				tv_price.setText("￥" + joCommodity.getString("price"));
				try{
					et_num.setText(joNumber.getInt("num_buy") + "");
				}catch(Exception e){
					et_num.setText("1");
				}
				ImageTask task = new ImageTask(ic_cover,Config.getFolderImages(),null);
				task.execute(joCommodity.getString("image"));
				tv_money_total.setText("合计：￥" + joCommodity.getLong("price") * Integer.parseInt(et_num.getText().toString()));
				tv_add.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						try{
							int last = Integer.parseInt(et_num.getText().toString()) + 1;
							et_num.setText(last + "");
							joNumber.put("num_buy", last);
							tv_money_total.setText("合计：￥" + joCommodity.getLong("price") * last);
						}catch(Exception e){
							et_num.setText("1");
							try {
								joNumber.put("num_buy", 1);
								tv_money_total.setText("合计：￥" + joCommodity.getLong("price") * 1);
							} catch (JSONException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
				});
				tv_divide.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						try{
							int last = Integer.parseInt(et_num.getText().toString()) - 1;
							if(last < 1){
								last = 1;
							}
							et_num.setText(last + "");
							joNumber.put("num_buy", last);
							tv_money_total.setText("合计：￥" + joCommodity.getLong("price") * last);
						}catch(Exception e){
							et_num.setText("1");
							try {
								joNumber.put("num_buy", 1);
								tv_money_total.setText("￥" + joCommodity.getLong("price") * 1);
							} catch (JSONException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
					}
				});
				layout_insurance.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						showToast("暂无运费险");
					}
				});
				layout_preferential.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						showToast("暂无相关优惠");
					}
				});
			}catch(JSONException e){
				
			}
			return convertView;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == CODE_BACK_FROM_SELECT_ADDRESS && resultCode == RESULT_OK && data != null){
			try {
				joAddress = new JSONObject(data.getStringExtra("addressData"));
				tv_address.setText(joAddress.getString("address"));
				tv_address_name.setText(joAddress.getString("name"));
				tv_address_mobile.setText(joAddress.getString("phone"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
}
